package com.gitee.shigen.gateway.config;

import java.util.Objects;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.gitee.shigen.gateway.enums.BalancerRuleTypeEnum;
import com.gitee.shigen.gateway.lb.AlwaysFirstRule;
import com.gitee.shigen.gateway.lb.NacosWeightedRule;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;

/**
 * 自定义负载均衡策略 <a href="https://blog.csdn.net/qq_38225558/article/details/121452527">参考文章</a>
 */
@Configuration
public class RibbonConfig {
    @Value("${ribbon.rule_type:first}")
    private String ruleType;

    @Bean
    public IRule getRule() {
        BalancerRuleTypeEnum ruleTypeEnum = BalancerRuleTypeEnum.getByName(ruleType);
        switch (Objects.requireNonNull(ruleTypeEnum)) {
            case NACOS_WEIGHTED:
                return new NacosWeightedRule();
            case FIRST:
                return new AlwaysFirstRule();
            default:
                return new RandomRule();
        }
    }
}
